$(function() {
	$('#my_tree_grid').jqGrid({
		url : "findListJson.do",
		height : "400px",
		autowidth:true,
		datatype: 'json',
		mtype: 'POST',
		ExpandColClick: true,
		ExpandColumn : "name",
		treeGrid: true,
		treeGridModel : "adjacency",
		treeReader : {
			"parent_id_field" : "parentId",
			"leaf_field" : "isLeafName",
			"level_field":"leve",
		},
		colModel : [ {
			"name" : "id",
			"key" : true,
			"hidden" : true
		}, 
		 {
			"name" : "name",
			"label" : "单位名称",
		}, {
			"name" : "code",
			"label" : "单位编码",
		}, {
			"name" : "parentName",
			"label" : "父级名称",
		} , {
			"name" : "areaName",
			"label" : "所属地区",
		},
		{name:'areaId', hidden:true  },
		{name:'parentId', hidden:true  },
		],
		pager: "false",  
		gridComplete: function(){
			var gridtree = $("#my_tree_grid");
			var row = gridtree.jqGrid("getLocalRow","0");
			gridtree.jqGrid('expandRow', row);
		},
		onSelectRow: function (rowid, status) {
			manageJobs();
		},
	}); 
	
	initAreaTree();
	initParentDeptTree();
	
	$("#grid-table").jqGrid({
		 url:'../jobs/findJobByDept.do',
		 postData:{'deptId':""},
		 mtype: 'POST',
		 datatype : "json",
		 autowidth:true, 
		 multiselect: true,
		 multiboxonly:true,
		 colModel:[
			{name:'id', hidden:true  },
			{name:'deptId', hidden:true  },
			{label:'人员类型名称',name:'name', width:"250",  editable:false  },
			{label:'人员类型编码', name:'code', width:"250", editable:false },
			 
		 ],
		 loadComplete : function() {
				updatePagerIcons(this);
				enableTooltips(this);
			},
		viewrecords : true,
		altRows: true,
		autowidth: true ,
		 
	}); 
	
	$(".btn-add").click(function(){
		addDept();
	});
	$(".btn-update").click(function(){
		editDept();
	});
	$(".btn-delete").click(function(){
		deleteDept();
	});
	$(".btn-type").click(function(){
		manageJobs();
	});
	$(".btn-jobs-add").click(function(){
		addJobs();
	});
	$(".btn-jobs-update").click(function(){
		editJobs();
	});
	$(".btn-jobs-delete").click(function(){
		deleteJobs();
	});
	
	validata();
});

function addDept(){
	clearform('deptform');
	selectAreaTreeNode('0');
	selectParentDeptTreeNode('0');
	show_panel("dept_panel");
}

function editDept(){
	var treegrid = $("#my_tree_grid");
	var rowId=treegrid.jqGrid('getGridParam','selrow');
	if(rowId == 0){
		$('#dept_panel').hide();
		return;
	}
	if( rowId == null){
		RM.msg("请选择要编辑的单位！");
		return;
	}
	var nodes = [];
	nodes[0] = treegrid.jqGrid('getRowData',rowId);
	if(nodes.length > 1){
		RM.msg("请只选择一个单位地区！");
		return;
	}
	clearform('deptform');
	show_panel("dept_panel");
	var rowsData = nodes[0];
	$('#form_id').val(rowsData.id);
    $('#form_name').val(rowsData.name);
    $('#form_code').val(rowsData.code);
    selectAreaTreeNode(rowsData.areaId);
	selectParentDeptTreeNode(rowsData.parentId);
	show_panel("dept_panel");
}

function deleteDept(){
	var treegrid = $("#my_tree_grid");
	var rowId=treegrid.jqGrid('getGridParam','selrow');
	if(rowId == 0){
		return;
	}
	if(rowId == null){
		RM.msg("请选择要删除的记录！");
		return;
	}
	var nodes = [];
	nodes[0] = treegrid.jqGrid('getRowData',rowId);
	if(nodes.length > 1){
		RM.msg("请只选择一个要删除的地区！");
		return;
	}
	RM.confirm("确认删除所选的记录吗?", function (){
		var rowsData = nodes[0];
		if(!postFlag){
			var callback = function(){
				var grid = $('#my_tree_grid');
				grid.jqGrid('setGridParam',{  datatype:'json',}).trigger("reloadGrid"); 
				initParentDeptTree();
			}
			sendMyAjax("del.do","id="+rowsData.id,callback);
			close_panel();
		}
		RM.close();
	});
}

function doDeptSave(){
	$("#deptform").submit();
}

/** jobs start**/
function manageJobs(){
	var treegrid = $("#my_tree_grid");
	var rowId=treegrid.jqGrid('getGridParam','selrow');
	if(rowId == 0){
		return;
	}
	if(rowId == null){
		RM.msg("请只选择一个单位！");
		return;
	}
	
	var nodes = [];
	nodes[0] = treegrid.jqGrid('getRowData',rowId);
	if(nodes == null  || nodes.length == 0){
		RM.msg("请选择先选择单位！");
		return;
	}
	var deptId = nodes[0].id;
	$("#form_job_dept").val(deptId);
	$("#grid-table").jqGrid('setGridParam',{  
        datatype:'json',  
        postData:{'deptId':deptId},
    }).trigger("reloadGrid"); //重新载入
	show_panel("jobs_panel");
}

function addJobs(){
	clearform('jobform');
	var deptId = $("#form_job_dept").val()
	RM.dialog("添加", $(".jobinfo").html());
	$(".layui-layer #form_job_dept").val(deptId);
	setTimeout(validata,1000);
}

function editJobs(){
	var grid = $("#grid-table");
	var ids = RM.jqgrid.ids(grid);
	if(ids.length == 0 || ids.length > 1){
		RM.msg("请选择一行数据进行编辑");
	}else{
		clearform('jobform');
		var rowsData = $('#grid-table').jqGrid('getRowData',ids[0]);
	    RM.dialog("编辑", $(".jobinfo").html());
	    $('.layui-layer #form_job_id').val(rowsData.id);
	    $('.layui-layer #form_job_name').val(rowsData.name);
	    $('.layui-layer #form_job_code').val(rowsData.code);
	    $('.layui-layer #form_job_dept').val(rowsData.deptId);
	}
	setTimeout(validata,1000);
}

function deleteJobs(){
	RM.jqgrid.dels($("#grid-table"),"../jobs/dels.do");
}

function doSaveJobs(){
	$(".layui-layer #jobform").submit();
}
/** area Tree start**/
var areaSetting = {
    view: {
    	selectedMulti: false,
    	dblClickExpand: false
    },
    check: {
        enable: false
    },
    data : {  
        key : {  
            name : "name"  
        },  
        simpleData : {  
            enable : true,  
            idKey : "id",  
            pIdKey : "parentId",  
            rootPId : 0  
        }  
    },   
    edit: {
        enable: false
    },
    callback: {
    	onClick: zTreeAreaOnClick
	}
};
function selectAreaTreeNode(id){
	var zTree_Menu = $.fn.zTree.getZTreeObj("treeDemoArea"); 
	var node = zTree_Menu.getNodeByParam("id",id );  
    zTree_Menu.selectNode(node,true);//指定选中ID的节点  
    zTree_Menu.expandNode(node, true, false);//指定选中ID节点展开
    
    $("#form_areaId").val(id);
    $("#areaName").val(node.name);
}
function initAreaTree(){
	$.post("../area/findAllJson.do",{},function (data){
 		$.fn.zTree.init($("#treeDemoArea"), areaSetting, data); 
	},"json");
}
function zTreeAreaOnClick(event, treeId, treeNode) {
    if (treeNode) {
    	$("#form_areaId").val(treeNode.id); 
        $("#areaName").val(treeNode.name);
    }
    hideAreaMenu();
}
function showAreaMenu() {
	var cityObj = $("#areaName");
	var cityOffset = $("#areaName").offset();
	$("#menuContentArea").css({left:0, top:"30px",width:$("#menuContentArea").closest(".input-group").width()}).slideDown("fast");
	$("body").bind("mousedown", onAreaBodyDown);
}
function hideAreaMenu() {
	$("#menuContentArea").fadeOut("fast");
	$("body").unbind("mousedown", onAreaBodyDown);
}
function onAreaBodyDown(event) {
	if (!(event.target.id == "menuAreaBtn" || event.target.id == "menuContentArea" || $(event.target).parents("#menuContentArea").length>0)) {
		hideAreaMenu();
	}
}

/** dept zTree start**/
var parentDeptSetting = {
    view: {
    	selectedMulti: false,
    	dblClickExpand: false
    },
    check: {
        enable: false
    },
    data : {  
        key : {  
            name : "name"  
        },  
        simpleData : {  
            enable : true,  
            idKey : "id",  
            pIdKey : "parentId",  
            rootPId : 0  
        }  
    },   
    edit: {
        enable: false
    },
    callback: {
    	onClick: zTreeParentDeptOnClick
	}
};
function selectParentDeptTreeNode(id){
	var zTree_Menu = $.fn.zTree.getZTreeObj("treeDemoParentDept"); 
	var node = zTree_Menu.getNodeByParam("id",id );  
    zTree_Menu.selectNode(node,true);//指定选中ID的节点  
    zTree_Menu.expandNode(node, true, false);//指定选中ID节点展开
    
    $("#form_parentId").val(id);
    $("#form_parentId2").val(node.parentId);
    $("#parentDeptSelectName").val(node.name);
}
function initParentDeptTree(){
	$.post("../dept/findAllJson.do",{},function (data){
 		$.fn.zTree.init($("#treeDemoParentDept"), parentDeptSetting, data); 
	},"json");
}
function zTreeParentDeptOnClick(event, treeId, treeNode) {
    if (treeNode) {
    	$("#form_parentId").val(treeNode.id); 
    	$("#form_parentId2").val(treeNode.parentId);
        $("#parentDeptSelectName").val(treeNode.name);
    }
    hideParentDeptMenu();
}
function showParentDeptMenu() {
	var cityObj = $("#parentDeptSelectName");
	var cityOffset = $("#parentDeptSelectName").offset();
	$("#menuContentParentDept").css({left:0, top:"30px",width:$("#menuContentParentDept").closest(".input-group").width()}).slideDown("fast");
	$("body").bind("mousedown", onParentDeptBodyDown);
}
function hideParentDeptMenu() {
	$("#menuContentParentDept").fadeOut("fast");
	$("body").unbind("mousedown", onParentDeptBodyDown);
}
function onParentDeptBodyDown(event) {
	if (!(event.target.id == "menuParentDeptBtn" || event.target.id == "menuContentParentDept" || $(event.target).parents("#menuContentParentDept").length>0)) {
		hideParentDeptMenu();
	}
}

var postFlag = false;

function clearform(formid){
	$('#'+formid)[0].reset();
    $("#"+formid+" :input").not(":button, :submit, :reset, .clear_save ").val("").removeAttr("checked").remove("selected"); 
    $("#"+formid+" .error").html("");
}

function sendMyAjax(url,data,callback){
	postFlag = true;
	$.ajax({
		   type: "POST",
		   url:url,
		   data:data, 
		   success: function(msg){
			   if(msg.code != '0'){
				  RM.alert(msg.message);
			   }else{
				 callback(); 
			   }
			   postFlag = false;
		   } ,
		   error: function(error){
			   RM.alert(error);
			   postFlag = false;
		   }
	});
}
function validata(){
	$("#deptform").validate({
		submitHandler: function() {
			if($("#form_areaId").val() == null){
				RM.alert("请选择地区");
				return null;
			}
			if(!postFlag){
				postFlag = true;
				$.ajax({
					   type: "POST",
					   url:"save.do",
					   data:$('#deptform').serialize(),// 要提交的表单
					   success: function(msg) {
						   var grid = $('#my_tree_grid');
						   grid.jqGrid('setGridParam',{datatype:'json', nodeid : null}).trigger("reloadGrid"); 
						   initParentDeptTree();
						   $('#dept_panel').hide();
						   RM.msg("操作成功！");
						   postFlag = false;
						},
					   error: function(error){
						   alert(error);
						   postFlag = false;
					   }
				});
			}
		}
	});
	
	$(".layui-layer #jobform").validate({
		submitHandler: function() {
			if(!postFlag){
				postFlag = true;
				$.ajax({
					   type: "POST",
					   url:"../jobs/save.do",
					   data:$('.layui-layer #jobform').serialize(),// 要提交的表单
					   success: function(msg) {
						   $("#grid-table").jqGrid().trigger("reloadGrid");  
						   RM.close();
						   postFlag = false;
						},
					   error: function(error){
						   alert(error);
						   postFlag = false;
					   }
				});
			}
		}
	});
}

function show_panel(p){
	if(p == "dept_panel"){
		$("#jobs_panel").hide();
	}else{
		$("#dept_panel").hide();
	}
	$("#"+p).show();
}
function close_panel(){
	$("#jobs_panel").hide();
	$("#dept_panel").hide();
}
